import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import { message as aMessage } from 'antd'
import { getToken } from './auth'
import { CodeMessage } from '@/config'

export interface Response<T> {
  code: number;
  data: T;
  message: string;
}

export const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_API_URL,
  timeout: 5000,
})

axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers!.token = token
    }
    return config
  },
  (error) => {
    console.error('error', error)
    aMessage.error('网络异常')
    return Promise.reject(error)
  },
)

axiosInstance.interceptors.response.use(
  (response:AxiosResponse<Response<any>>) => {
    const { code, message, data } = response.data
    if (code !== 0) {
      aMessage.error(message)
      return Promise.reject(new Error(message))
    }
    return Promise.resolve(data)
  },
  (error) => {
    httpErrorStatusHandler(error)
    return Promise.reject(error)
  },
)

export const request = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return axiosInstance.get(url, config)
  },
  post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return axiosInstance.post(url, data, config)
  },
  put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return axiosInstance.put(url, data, config)
  },
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return axiosInstance.delete(url, config)
  },
}

export function httpErrorStatusHandler(error: AxiosError) {
  let message = ''
  if (error?.response?.status) {
    message = CodeMessage[error.response.status]
  }
  if (error.message.includes('timeout')) message = '网络请求超时！'
  if (error.message.includes('Network')) message = window.navigator.onLine ? '服务端异常！' : '您断网了！'
  error.message = message
  aMessage.error(message)
}
